package com.carefree.bookmall.controller;

import com.carefree.bookmall.common.utils.Constant;
import com.carefree.bookmall.common.vo.BookQueryVo;
import com.carefree.bookmall.common.vo.PageVO;
import com.carefree.bookmall.entity.Book;
import com.carefree.bookmall.entity.BookType;
import com.carefree.bookmall.entity.User;
import com.carefree.bookmall.exception.CustomException;
import com.carefree.bookmall.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:AdminController
 * @Description: 后台管理
 * @Author Tengbin
 */
@Controller
@RequestMapping("/bookmall/admin")
public class AdminController {

    @Resource
    private UserService userService;

    @Resource
    private OrderService orderService;

    @Resource
    private BookService bookService;

    @Resource
    private BookTypeService bookTypeService;

    @Resource
    private AliCloudService aliCloudService;


    /**
     * 修改密码
     *
     * @param id          主键id
     * @param oldpassword 旧密码
     * @param newpassword 新密码
     * @param request
     * @return
     */
    @PostMapping("/reset")
    public String updatePassword(Integer id, String oldpassword, String newpassword, HttpServletRequest request) throws Exception {
        // 执行db修改密码
        boolean flag = userService.updatePassword(id, oldpassword, newpassword);

        if (flag) {
            request.setAttribute(Constant.MESSAGE, Constant.UPDATE_MESSAGE_SUCCESS);
        } else {
            request.setAttribute(Constant.FAIL_MESSAGE, Constant.UPDATE_MESSAGE_FAIL);
        }
        return "admin/reset_password";
    }


    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.SESSION_USER);
        request.getSession().removeAttribute(Constant.SESSION_ORDER);
        return "redirect:/bookmall/index";
    }


    /**
     * 用户列表
     *
     * @param pageNum
     * @param request
     * @return
     */
    @GetMapping("/users")
    public String queryUsers(int pageNum, HttpServletRequest request) {

        PageVO pageVO = userService.queryUser(pageNum, 7);

        if (pageVO.getTotalPage() == 0) {
            pageVO.setTotalPage(1);
            pageVO.setPageNumber(1);
        } else {
            if (pageNum >= pageVO.getTotalPage() + 1) {
                pageVO = userService.queryUser(pageVO.getTotalPage(), 7);
            }
        }
        request.setAttribute("page", pageVO);
        return "admin/user_list";
    }


    /**
     * 删除用户
     *
     * @param userId  主键id
     * @param request
     * @return
     */
    @GetMapping("/user/remove/{userId}")
    @ResponseBody
    public boolean deleteUser(@PathVariable Integer userId, HttpServletRequest request) throws CustomException {
        return userService.deleteUser(userId);
    }

    /**
     * 修改用户
     *
     * @param userId  主键id
     * @param request
     * @return
     */
    @GetMapping("/user/query/{userId}")
    @ResponseBody
    public User queryUserById(@PathVariable Integer userId, HttpServletRequest request) throws CustomException {
        User user = userService.queryUserByUserId(userId);

        if (ObjectUtils.isEmpty(user)) {
            request.setAttribute(Constant.FAIL_MESSAGE, Constant.UPDATE_MESSAGE_FAIL);
            return null;
        }
        user.setPassword("");

        return user;
    }

    /**
     * 修改用户信息
     *
     * @param tempUser 修改的用户对象
     * @param request
     * @return
     */
    @PostMapping("/user/edit")
    public String updateAdminProfile(User user, HttpServletRequest request) throws CustomException {
        userService.updateUserSeletive(user);
        return "redirect:/bookmall/admin/users?pageNum=1";
    }

    /**
     * 添加用户
     *
     * @param tempUser
     * @param request
     * @return
     */
    @PostMapping("/user/insert")
    @ResponseBody
    public boolean insertUserProfile(User user, HttpServletRequest request) throws Exception {
        return userService.register(user);
    }


    /**
     * 重置密码
     *
     * @param id          主键id
     * @param newpassword 新密码
     * @return
     */
    @PostMapping("/user/reset")
    public String resetUserPassword(Integer id, String newpassword, HttpServletRequest request) throws Exception {

        userService.updatePassword(id, newpassword);

        return "redirect:/bookmall/admin/users?pageNum=1";
    }


    /**
     * 订单列表
     *
     * @param status  状态
     * @param pageNum 页码
     * @param request
     * @return
     */
    @GetMapping("/orders/{status}")
    public String queryOrders(@PathVariable Integer status, int pageNum, HttpServletRequest request) {

        PageVO pageVO = orderService.queryOrdersByStatus(status, pageNum, 5);

        if (pageVO.getTotalPage() == 0) {
            pageVO.setTotalPage(1);
            pageVO.setPageNumber(1);
        } else {
            if (pageNum >= pageVO.getTotalPage() + 1) {
                pageVO = orderService.queryOrdersByStatus(status, pageVO.getTotalPage(), 5);
            }
        }
        request.setAttribute("status", status);
        request.setAttribute("page", pageVO);

        return "admin/order_list";
    }


    /**
     * 修改订单状态
     *
     * @param id      主键id
     * @param status  状态值
     * @param request
     * @return
     */
    @GetMapping("/order/change")
    public String changeOrderStatus(String id, Integer status, HttpServletRequest request) throws CustomException {
        orderService.updateOrderStatus(id, status);
        return "redirect:/bookmall/admin/orders/" + status + "?pageNum=1";
    }


    /**
     * 删除订单
     *
     * @param id      主键id
     * @param status  原订单状态值
     * @param request
     * @return
     */
    @GetMapping("/order/remove/{id}")
    @ResponseBody
    public boolean deleteOrder(@PathVariable String id, HttpServletRequest request) throws CustomException {
        return orderService.deleteOrderByOrderId(id);
    }


    /**
     * 商品列表
     *
     * @param recommendType 推荐类型
     * @param pageNum       页码
     * @param request
     * @return
     */
    @GetMapping("/books/{recommendType}")
    public String queryBooks(@PathVariable String recommendType, int pageNum, HttpServletRequest request) throws CustomException {

        PageVO pageVO = bookService.pageBookByRecommendType(recommendType, pageNum, 6);

        if (pageVO.getTotalPage() == 0) {
            pageVO.setTotalPage(1);
            pageVO.setPageNumber(1);
        } else {
            if (pageNum >= pageVO.getTotalPage() + 1) {
                pageVO = bookService.pageBookByRecommendType(recommendType, pageVO.getTotalPage(), 6);
            }
        }
        request.setAttribute("page", pageVO);

        request.setAttribute("recommendType", recommendType);
        return "admin/book_list";
    }


    /**
     * 添加商品
     *
     * @return
     */
    @PostMapping("/book/insert")
    @ResponseBody
    public boolean addBook(Book book) throws CustomException {
        return bookService.addBook(book);
    }


    /**
     * 删除书籍
     *
     * @param bookId
     * @return
     */
    @GetMapping("/book/remove/{bookId}")
    @ResponseBody
    public boolean removeBookById(@PathVariable Integer bookId) throws CustomException {
        return bookService.removeBookByBookId(bookId);
    }


    /**
     * 后台 商品详情
     *
     * @param bookId
     * @return
     */
    @GetMapping("/book/show/{bookId}")
    @ResponseBody
    public BookQueryVo showBookDetailById(@PathVariable Integer bookId, HttpServletRequest request) throws CustomException {
        return bookService.queryBookByBookId(bookId);
    }


    @PostMapping("/book/update")
    @ResponseBody
    public boolean editBookInfo(Book book) throws CustomException {
        // 根据当前编辑的商品id查询原商品信息
        Book queryBook = bookService.queryBookById(book.getId());

        // 初始化oss删除图片路径集合
        List<String> deleteImagesUrl = new ArrayList<>();

        if (! queryBook.getCover().equals(book.getCover())) {
            deleteImagesUrl.add(queryBook.getCover().substring(52));

        } else if (! queryBook.getImage1().equals(book.getImage1())) {
            deleteImagesUrl.add(queryBook.getImage1().substring(52));

        } else if (! queryBook.getImage2().equals(book.getImage2())) {
            deleteImagesUrl.add(queryBook.getImage2().substring(52));
        } else {
            return bookService.modifyBook(book);
        }

        if (aliCloudService.deleteUploadedImage(deleteImagesUrl)) {
            return bookService.modifyBook(book);
        }

        return false;
    }


    /**
     * 条幅、热销、新品的加入和移除
     *
     * @param bookId    商品id
     * @param recommend 推荐类型（1条幅；2热销；3新品）
     * @param method    加入或移除（add/remove）
     * @return
     */
    @GetMapping("/book/edit/{bookId}")
    public String editBookForRecommend(@PathVariable Integer bookId, Integer recommend, String method) throws CustomException {
        if ("add".equals(method)) {
            bookService.addRecommend(bookId, recommend);
        } else {
            bookService.remoteRecommend(bookId, recommend);
        }
        return "redirect:/bookmall/admin/books/all?pageNum=1";
    }


    /**
     * 类目列表
     *
     * @param pageNum
     * @param request
     * @return
     */
    @GetMapping("/types")
    public String queryTypes(int pageNum, HttpServletRequest request) {
        PageVO pageVO = bookTypeService.queryBookTypes(pageNum, 6);
        if (pageVO.getTotalPage() == 0) {
            pageVO.setTotalPage(1);
            pageVO.setPageNumber(1);
        } else {
            if (pageNum >= pageVO.getTotalPage() + 1) {
                pageVO = bookTypeService.queryBookTypes(pageVO.getTotalPage(), 6);
            }
        }
        request.setAttribute("page", pageVO);

        return "admin/type_list";
    }


    /**
     * 根据类目id回显修改页面数据
     *
     * @param typeId
     * @return
     */
    @GetMapping("/type/{typeId}")
    @ResponseBody
    public BookType queryBookTypeById(@PathVariable Integer typeId) throws CustomException {
        return bookTypeService.queryBookTypeById(typeId);
    }


    /**
     * 编辑类目
     *
     * @param bookType
     * @param request
     * @return
     */
    @PostMapping("/type/edit")
    @ResponseBody
    public boolean insertType(BookType bookType) {
        boolean flag = true;

        if (bookType.getId() != null) {
            // 修改
            flag = bookTypeService.modifyBookType(bookType);
        } else {
            // 新增
            flag = bookTypeService.addBookType(bookType);
        }
        return flag;
    }

    /**
     * 删除类目（物理删除）
     *
     * @param typeId
     * @return
     */
    @GetMapping("/type/remove/{typeId}")
    @ResponseBody
    public boolean deleteBookTypeById(@PathVariable Integer typeId) throws CustomException {
        return bookTypeService.removeBookType(typeId);
    }


}
